/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufes.ceunes.poo.view.cadastros;

import br.ufes.ceunes.poo.model.dao.DAOGenerico;
import br.ufes.ceunes.poo.model.dao.FornecedorDAO;
import br.ufes.ceunes.poo.model.dao.ProdutoDAO;
import br.ufes.ceunes.poo.model.pojo.Fornecedor;
import br.ufes.ceunes.poo.model.pojo.Produto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author jefferson Martins
 */
public class CadastroProduto extends javax.swing.JFrame {
    
    private Produto produto;
    private DAOGenerico daoProduto;
    
    public CadastroProduto() {
        initComponents();
        botoesAcoes();
        produto = new Produto();
        daoProduto = new ProdutoDAO();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txNome = new javax.swing.JTextField();
        lFornecedor = new javax.swing.JLabel();
        bCancelar = new javax.swing.JButton();
        bCadastrar = new javax.swing.JButton();
        lTitulo = new javax.swing.JLabel();
        lPreco = new javax.swing.JLabel();
        txPreco = new javax.swing.JTextField();
        lQuantidade = new javax.swing.JLabel();
        txQuantidade = new javax.swing.JTextField();
        lNome = new javax.swing.JLabel();
        bSelecionar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaFornecedor = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro Produto");

        txNome.setToolTipText("");
        txNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txNomeActionPerformed(evt);
            }
        });

        lFornecedor.setText("Fornecedor*:");

        bCancelar.setText("Cancelar");

        bCadastrar.setText("Cadastrar");

        lTitulo.setText("Cadastro de Produto");

        lPreco.setText("Preço*:");

        txPreco.setToolTipText("");
        txPreco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txPrecoActionPerformed(evt);
            }
        });

        lQuantidade.setText("Quantidade*:");

        txQuantidade.setToolTipText("");

        lNome.setText("Nome*:");

        bSelecionar.setText("Selecionar");
        bSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSelecionarActionPerformed(evt);
            }
        });

        tabelaFornecedor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nome"
            }
        ));
        preencherTabelaFornecedor();
        jScrollPane1.setViewportView(tabelaFornecedor);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lNome)
                            .addComponent(lPreco))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txNome)
                            .addComponent(txQuantidade, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txPreco, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(61, 61, 61))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lTitulo)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(bSelecionar)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lFornecedor)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bCadastrar)
                                .addGap(18, 18, 18)
                                .addComponent(bCancelar)))
                        .addGap(0, 10, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lTitulo)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lNome)
                    .addComponent(txNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lPreco)
                    .addComponent(txPreco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lQuantidade)
                    .addComponent(txQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lFornecedor)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bSelecionar)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCancelar)
                    .addComponent(bCadastrar))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txNomeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txNomeActionPerformed

    private void txPrecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txPrecoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txPrecoActionPerformed

    private void bSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSelecionarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_bSelecionarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastroProduto().setVisible(true);
            }
        });
    }

    private void preencherTabelaFornecedor() {
        DefaultTableModel model = (DefaultTableModel) tabelaFornecedor.getModel();
        List<Fornecedor> fornecedores = new FornecedorDAO().listar();
        for (Fornecedor f : fornecedores) {
            model.addRow(new Object[]{null, null});
            model.setValueAt(f.getId(), model.getRowCount() - 1, 0);
            model.setValueAt(f.getNome(), model.getRowCount() - 1, 1);
        }
    }

    private void botoesAcoes() {
        bSelecionar.addActionListener(new ActionListener() {
            private DAOGenerico fornecedorDAO;
            
            @Override
            public void actionPerformed(ActionEvent e) {
                fornecedorDAO = new FornecedorDAO();
                int options[] = tabelaFornecedor.getSelectedRows();
                DefaultTableModel modelo = (DefaultTableModel) tabelaFornecedor
                        .getModel();
                for (int i : options) {
                    Integer id = (Integer)(((Vector)modelo.getDataVector().
                            elementAt(i)).elementAt(0));
                    produto.adicionaFornecedor((Fornecedor)fornecedorDAO.
                            buscarPorId(id));
                }
            }
        });
        
        bCadastrar.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                produto = new Produto();
                produto.setNome(txNome.getText());
                produto.setPreco(Double.parseDouble(txPreco.getText()));
                daoProduto.salvar(produto);
            }
        
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCadastrar;
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bSelecionar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lFornecedor;
    private javax.swing.JLabel lNome;
    private javax.swing.JLabel lPreco;
    private javax.swing.JLabel lQuantidade;
    private javax.swing.JLabel lTitulo;
    private javax.swing.JTable tabelaFornecedor;
    private javax.swing.JTextField txNome;
    private javax.swing.JTextField txPreco;
    private javax.swing.JTextField txQuantidade;
    // End of variables declaration//GEN-END:variables
}
